//
//  YHYAddPictureCollectionViewCell.m
//  Home
//
//  Created by 杨泓晔 on 16/6/4.
//  Copyright © 2016年 LanJue. All rights reserved.
//

#import "YHYAddPictureCollectionViewCell.h"
#import "TZTestCell.h"
#import "UIView+Layout.h"
#import "YHYPictureCollectionViewCell.h"
#import "SeaPictureViewController.h"
#import "TZImagePickerController.h"
@interface YHYAddPictureCollectionViewCell ()<UICollectionViewDataSource,UICollectionViewDelegate,TZImagePickerControllerDelegate>{
    NSInteger index;
    CGFloat _itemWH;
    CGFloat _margin;
    
    NSMutableArray *_selectedAssets;
    
    
    NSIndexPath *indexP;

}

@property (nonatomic,strong)UICollectionViewFlowLayout *layout;
@property (nonatomic,strong)UICollectionView *myCollectionView;
@property (nonatomic,strong)UILabel *numLabel;
@property (nonatomic,strong)UIButton *button;


@property (nonatomic,retain)NSIndexPath *myindexPath;
@property (nonatomic,retain)NSMutableArray *seaArr;
@property (nonatomic,retain)UILabel *textnameL;
@property (nonatomic,retain)NSIndexPath *tapIndexPath;

@end

@implementation YHYAddPictureCollectionViewCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
       
        
//  
//         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(change:) name:@"arr" object:nil];
        
        [self creatView];
        [_myCollectionView reloadData];

    }
    return self;
}


- (void)creatView{
    _selectedPhotos = [NSMutableArray array];
    _selectedAssets = [NSMutableArray array];
    self.myindexPath = [NSIndexPath new];
    _seaArr = [NSMutableArray array];
    self.numLabel = [UILabel new];
    self.tapIndexPath = [NSIndexPath new];
    
    
    self.layout = [[UICollectionViewFlowLayout alloc] init];
    _margin = 4 * AUTO_HEIGHT;
    _itemWH = (self.contentView.tz_width - 20 * AUTO_WIDTH-2 * _margin - 7) / 3 - _margin;
    self.layout.itemSize = CGSizeMake(_itemWH, _itemWH  - 1 );
    self.layout.minimumInteritemSpacing = _margin;
    self.layout.minimumLineSpacing = 10  * AUTO_HEIGHT ;
    _myCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0 * AUTO_WIDTH, SCREEN_WIDTH, _itemWH * 3 + _margin + 6 * AUTO_HEIGHT + 50 * AUTO_HEIGHT- 15 * AUTO_HEIGHT) collectionViewLayout:self.layout];
    self.myCollectionView.backgroundColor = [UIColor whiteColor];
    //    裁掉view的边界
    self.myCollectionView.layer.masksToBounds = NO;
    //    设置半径
    //self.myCollectionView.layer.cornerRadius = 6 * AUTO_WIDTH;
    self.myCollectionView.scrollEnabled = NO;
    // self.myCollectionView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:_myCollectionView];
    
    
    
    
    
    _myCollectionView.contentInset = UIEdgeInsetsMake(13 * AUTO_WIDTH, 15 * AUTO_HEIGHT, 5 * AUTO_WIDTH, 15 * AUTO_HEIGHT);
    _myCollectionView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, -2 * AUTO_HEIGHT);
    _myCollectionView.dataSource = self;
    _myCollectionView.delegate = self;
    _myCollectionView.backgroundColor = [UIColor whiteColor];
    [_myCollectionView registerClass:[TZTestCell class] forCellWithReuseIdentifier:@"TZTestCell"];
    
    [_myCollectionView registerClass:[YHYPictureCollectionViewCell class] forCellWithReuseIdentifier:@"YHYPicCollectionViewCell"];
    UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(buttonLongPressed:)];
    [_myCollectionView addGestureRecognizer:longGesture];
    
    
    
    self.numLabel = [UILabel new];
    [self.contentView addSubview:self.numLabel];
    self.numLabel.textColor = [UIColor blackColor];
    self.numLabel.alpha = 0.6;
    self.numLabel.font = [UIFont systemFontOfSize:TEXTLABELFONT*TEXTWEIGHT];
    [self.numLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_myCollectionView.mas_bottom).offset(11 * AUTO_HEIGHT);
        make.left.mas_equalTo(self.contentView.mas_right).offset( - 50  * AUTO_WIDTH);
        make.height.mas_equalTo(15 * AUTO_WIDTH);
        
    }];
    // NSLog(@"zzzzzzz%ld",(unsigned long)_selectedPhotos.count);
    self.numLabel.text = [NSString stringWithFormat:@"%ld/9",(long)_selectedPhotos.count];
    

    [_myCollectionView reloadData];
}

- (void)buttonLongPressed:(UILongPressGestureRecognizer *)longPress
{
    switch (longPress.state) {
        case UIGestureRecognizerStateBegan:
        {
            
            NSIndexPath *selectedIndex = [[NSIndexPath alloc] init];
            CGPoint point = [longPress locationInView:_myCollectionView];
            selectedIndex = [_myCollectionView indexPathForItemAtPoint:point];
            [_myCollectionView beginInteractiveMovementForItemAtIndexPath:selectedIndex];
            TZTestCell *mycell = (TZTestCell *)[_myCollectionView cellForItemAtIndexPath:selectedIndex];
            if (selectedIndex.row == _selectedPhotos.count) {
                //左后一个不抖动
            }
            else{
                [self shakeAnimationForView:mycell.imageView point:point];
            }
            
        }
            break;
        case UIGestureRecognizerStateChanged:
        {
            [_myCollectionView updateInteractiveMovementTargetPosition:[longPress locationInView:_myCollectionView]];
        }
            break;
        case UIGestureRecognizerStateEnded:
        {
            // 啥意思打上注释:就是当他移动时，到边距ok，移动到一定位置就删除
            [_myCollectionView endInteractiveMovement];
            NSIndexPath *selectedIndex = [[NSIndexPath alloc] init];
            CGPoint point = [longPress locationInView:_myCollectionView];
            selectedIndex = [_myCollectionView indexPathForItemAtPoint:point];
            if (point.x < 50 || point.y < 50 || point.x > _itemWH * 3  - 30 || point.y > _itemWH * 3  - 40) {
                //          是图片
                [_selectedPhotos removeObjectAtIndex:_myindexPath.item];
                //   [_selectedPhotos removeObject:selectObject];
                //                 NSLog(@"%@",_selectedPhotos);
                //                NSLog(@"zzzzzzz%ld",(unsigned long)_selectedPhotos.count);
                self.numLabel.text = [NSString stringWithFormat:@"%ld/9",(long)_selectedPhotos.count];
                //                NSLog(@"sssssssss%ld",(long)_myindexPath.row);
                
                NSLog(@"-------%ld", _selectedPhotos.count);
                
                
                
                
                
                //
                //                TZTestCell *mycell = (TZTestCell *)[_myCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:_selectedPhotos.count inSection:0]];
                //                mycell.imageView.image = [UIImage imageNamed:@"jia"];
                //
                
                [_myCollectionView reloadData];
                // [_myTableView reloadData];
            }
            // NSLog(@"asasasas%@",_selectedPhotos);
            
            
        }
            
            break;
        default:
            [_myCollectionView cancelInteractiveMovement];
            break;
    }
    
    
}

- (void)shakeAnimationForView:(UIView *)view point:(CGPoint)point{
    //获取到当前的View
    CALayer *viewLayer = view.layer;
    //获取当前View位置
    CGPoint position = viewLayer.position;
    CGPoint x = CGPointMake(position.x + 9, position.y);
    CGPoint y = CGPointMake(position.x - 9, position.y);
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    [animation setFromValue:[NSValue valueWithCGPoint:x]];
    [animation setToValue:[NSValue valueWithCGPoint:y]];
    [animation setAutoreverses:YES];
    [animation setDuration:0.06];
    [animation setRepeatCount:3];
    [viewLayer addAnimation:animation forKey:nil];
    
    
    
}


//通知响应方法
- (void)change:(NSNotification *)notification
{
    NSMutableArray *ar = [notification object];
    self.selectedPhotos = ar;
    NSLog(@"qqqq%@",ar);
    self.numLabel.text = [NSString stringWithFormat:@"%ld/9",(long)_selectedPhotos.count];
    [_myCollectionView reloadData];
    
}

- (void)setSelectedPhotos:(NSMutableArray *)selectedPhotos{
//    NSLog(@"qwqwqwqw%@",selectedPhotos);
    _selectedPhotos = selectedPhotos;
    [_myCollectionView reloadData];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    NSLog(@"number:%ld", _selectedPhotos.count);
    if (_selectedPhotos.count >= 9) {
        return _selectedPhotos.count;
    }
    else{
        return _selectedPhotos.count + 1;
        
    }
    
    
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    //改
    //    self.cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TZTestCell" forIndexPath:indexPath];
    
    
//    NSLog(@"row:%ld count:%ld", indexPath.row, _selectedPhotos.count);
    
    if (indexPath.row == _selectedPhotos.count) {
        YHYPictureCollectionViewCell *cell1 = [collectionView   dequeueReusableCellWithReuseIdentifier:@"YHYPicCollectionViewCell" forIndexPath:indexPath];
        // cell1.imageI = [UIImage imageNamed:@"jia"];
        cell1.backgroundColor = [UIColor redColor];
        return cell1;
        
    }
    else{
        TZTestCell *cell =  [collectionView dequeueReusableCellWithReuseIdentifier:@"TZTestCell" forIndexPath:indexPath];
        //        cell.imageI = _selectedPhotos[indexPath.row];
        
        cell.imageView.image = _selectedPhotos[indexPath.row];
        return cell;
        
        
        
        
    }
    
    
  }


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == _selectedPhotos.count) {
        
        
       // [self pickPhotoButtonClick:nil];
        [self.delegate present:_selectedPhotos.count selectArray:_selectedPhotos];
        
    }
    else{
        //        YHYYHYYHYViewController *yhySeaVC = [YHYYHYYHYViewController new];
        
        SeaPictureViewController *yhySeaVC = [SeaPictureViewController new];
        yhySeaVC.seaArray  = [NSMutableArray arrayWithArray:_selectedPhotos];
        yhySeaVC.indexNumber = (NSInteger)indexPath.item;
        
        NSLog(@"sssssss%ld",yhySeaVC.indexNumber);
        //        [self presentViewController:yhySeaVC animated:YES completion:^{
        //
        //
        //        }];
        //        [self.navigationController presentViewController:yhySeaVC animated:YES completion:^{
        //
        //
        //        }];
        //
        
        
        
        
//?       [self.navigationController pushViewController:yhySeaVC animated:YES];
        
        
        
        
    }
    //  [_myCollectionView reloadData];//改
    
}
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    _myindexPath = indexPath;
    if ([collectionView numberOfItemsInSection:indexPath.section] <= 1) {
        return NO;
    }
    if (indexPath.row == _selectedPhotos.count) {
        return NO;
    }
    
    return YES;
}


- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    
    
    _tapIndexPath = sourceIndexPath;
    
    
    if (destinationIndexPath.row != _selectedPhotos.count) {
        
        
        NSString *selectObject = _selectedPhotos[sourceIndexPath.item];
        self.myindexPath = sourceIndexPath;
        //从资源数组中移除该数据
        [_selectedPhotos removeObject:selectObject];
        
        
        
        
        
        
        NSMutableArray *destinationArr = _selectedPhotos;
        [destinationArr insertObject:selectObject atIndex:destinationIndexPath.row];
        _selectedPhotos = [NSMutableArray arrayWithArray:destinationArr];
        
    }else{
#pragma mark -后改动的
        
        //        TZTestCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TZTestCell" forIndexPath:[NSIndexPath indexPathForItem:_selectedPhotos.count inSection:0]];
        //
        //            cell.imageView.image = [UIImage imageNamed:@"jia"];
        //
        
        
    }
    
    
    //    _cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TZTestCell" forIndexPath:[NSIndexPath indexPathForItem:_selectedPhotos.count inSection:0]];
    //
    //
    //    _cell.imageView.image = [UIImage imageNamed:@"jia"];
    
    [collectionView reloadData];
    
    
}


#pragma mark Click Event

//- (IBAction)pickPhotoButtonClick:(UIButton *)sender {
//      NSInteger mum = 9;
//    
//    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc]initWithMaxImagesCount:mum selectArr:_selectedPhotos delegate:self];
//    imagePickerVc.selectCount = _selectedPhotos.count;
//    //    NSLog(@"asas%ld",(long)imagePickerVc.selectCount);
//    [self presentViewController:imagePickerVc animated:YES completion:nil];
//    
//    
//    
//}
//

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets{
    [_selectedPhotos addObjectsFromArray:photos];
    
     NSLog(@"wwww%ld",(unsigned long)photos.count);
    //[self configCollectionView];
    
    _myCollectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));
    
    
    self.numLabel.text = [NSString stringWithFormat:@"%ld/9",(long)_selectedPhotos.count];
    
    [_myCollectionView reloadData];
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

  //  NSLog(@"WH:%f", _itemWH);
    return CGSizeMake(_itemWH, _itemWH);

}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 2.0 * AUTO_WIDTH, 0);
}




@end
